using System;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;

namespace Caramel.ServiceModel
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
	public class UnitOfWorkPerCallAttribute : Attribute, IOperationBehavior
	{
		public UnitOfWorkPerCallAttribute()
			: this(true)
		{
		}

		public UnitOfWorkPerCallAttribute(bool autoCommit)
		{
			this.AutoCommit = autoCommit;
		}

		public bool AutoCommit { get; protected set; }

		#region IOperationBehavior Members

		void IOperationBehavior.AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
		{
		}

		void IOperationBehavior.ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
		{
		}

		void IOperationBehavior.ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
		{
			dispatchOperation.
				CallContextInitializers.
				Add(new UnitOfWorkCallContextInitializer(this.AutoCommit));
		}

		void IOperationBehavior.Validate(OperationDescription operationDescription)
		{
		}

		#endregion
	}
}
